package com.aos.controller;

import com.aos.client.GetUserTokenClient;
import com.aos.entity.User;
import com.aos.exception.BusinessException;
import com.aos.exception.ResultStatus;
import com.aos.service.UserEntryService;
import com.aos.service.user.UserService;
import com.aos.util.AssertUtil;
//import com.aos.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.aos.entity.JWT;

import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by quxiaoyan
 * 用户准入/Token分发
 */
@RestController
@RequestMapping("/entry")
@Api(value = "Entry Controller", tags = {"准入接口"})
public class EntryController {

    private static Logger log = LoggerFactory.getLogger(EntryController.class);

    @Autowired
    UserService userService;

    @Autowired
    UserEntryService userEntryService;

    @Autowired
    GetUserTokenClient getUserTokenClient;

    /**
     * 用户准入校验
     * @param {String} userName 用户名
     * @param {String} password 密码
     * @param {String} type 登录类型
     * @param {String} service_id 服务名
     * @param {String} secret Client密码
     * @return map
     */
    @ApiOperation(value = "用户准入校验", notes = "准入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名",   required = true,paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "login_type", value = "登录类型",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "service_id", value = "服务名",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "secret", value = "服务密码", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public Object entry(@RequestParam(value = "username",required = false) String userName,
                        @RequestParam(value = "password",required = false) String password ,
                        @RequestParam(value = "login_type",required = false) String loginType,
                        @RequestParam(value = "service_id",required = false) String serviceId,
                        @RequestParam(value = "secret",required = false) String secret) throws UnsupportedEncodingException {

        System.out.println("username:"+ userName);
        System.out.println("password:"+ password);
        System.out.println("secret:"+ secret);

//        if(userName == null){
//            return Result.error("登录用户名不能为空！");
//        }
//        if(password == null){
//            return Result.error("登录密码不能为空！");
//        }
//        if(loginType == null){
//            return Result.error("登录类型不能为空！");
//        }
//        if(serviceId == null){
//            return Result.error("服务名不能为空！");
//        }
        AssertUtil.notNull(userName.trim(), "登录用户名为空");
        AssertUtil.notNull(password, "登录密码为空");
        AssertUtil.notNull(loginType, "登录类型为空");
        AssertUtil.notNull(serviceId, "服务名为空");

        //返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("username",userName);
        map.put("service_id",serviceId);

        //校验登录类型：PA-用户名/密码类型，FI-指纹，FA-面部识别，ID-身份证
        if(loginType.trim().equals("PA"))   //用户名/密码类型
        {
            System.out.println("=====开始执行用户准入校验=====");
            //用户准入校验
            User user = userService.checkUser(userName,password);

            //用户准入校验通过后，获取Token
            String token = userEntryService.getToken(user.getUid().toString(),password+"{" + user.getSalt() + "}",serviceId,secret,"password");
            map.put("access_token",token);
            //String token = "";
            if(token==null || token.trim().equals(""))
            {
                log.debug("Token获取失败！");
                //return Result.error("Token获取失败！");
                throw new BusinessException("Token获取失败！", ResultStatus.fail.toString());
            }

            map.put("access_token",token);
        }
        else if (loginType.trim().equals("FI")){   //指纹类型

        }
        else if (loginType.trim().equals("FA")){    //面部识别类型

        }
        else if (loginType.trim().equals("ID")){    //身份证类型

        }


        return map;


    }

    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Principal getUser(Principal principal) {
        return principal;
    }


    /************************以下方法为测试用************************/
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
//    public String test (){
//        System.out.println("================调用test================");;
//
//        return "调用test";
//    }
//
//    @RequestMapping(value = "/delete",method = RequestMethod.POST)
//    public String delete (@RequestParam("access_token") String access_token){
//        System.out.println("================调用delete================");
//        String token = getUserTokenClient.deletetToken(access_token);
//        return token;
//    }

}
